import { defineResponseResolver } from '~~/mocks/define';

import db from '~/DB';
import { v4 as uuidv4 } from 'uuid';
import { Status } from '~~/DB/types/status.d';
import { TokenType } from '~~/DB/types/token.d';

export default defineResponseResolver(async (req, res, ctx) => {
  console.log(
    '🚀 ~ file: [type].post.ts:9 ~ defineResponseResolver ~ req:',
    req,
  );
  // const type
  const body = await req.json();

  switch (req.params.type) {
    case 'password': {
      break;
    }
    default: {
      return res(
        ctx.status(400),
        ctx.json({ error: 'typeError', message: '未知的登录方式' }),
      );
    }
  }

  const user = await db.users.get({
    name: body.userName,
    password: body.password,
  });

  if (!user) {
    return res(
      ctx.status(400),
      ctx.json({ error: 'passwordError', message: '账号或密码错误' }),
    );
  }

  if (user.status === Status.disable) {
    return res(
      ctx.status(403),
      ctx.json({ error: 'userDisable', message: '账户已被禁用，请联系管理员' }),
    );
  }

  const token = uuidv4();

  // token是一个易失数据，其实应该使用缓存降低数据库开销，但这里是模拟服务不做考虑

  // 查找旧的token进行覆盖
  const oldToken = await db.tokens.get({
    uid: user.uid,
    type: TokenType.token,
  });

  await db.tokens.put({
    id: oldToken?.id,
    token,
    uid: user.uid,
    status: Status.enable,
    type: TokenType.token,
    createTime: new Date(),
    expirationTime: new Date(Date.now() + 1000 * 60 * 10),
  });

  // refreshToken的设计是为了实现拥有较长有效期的token， 无需在每次请求时延长token有效期，避免了数据的频繁读写。
  const refreshToken = uuidv4();

  const oldRefreshToken = await db.tokens.get({
    uid: user.uid,
    type: TokenType.refreshToken,
  });

  await db.tokens.put({
    id: oldRefreshToken?.id,
    token: refreshToken,
    uid: user.uid,
    status: Status.enable,
    type: TokenType.refreshToken,
    createTime: new Date(),
    expirationTime: new Date(Date.now() + 1000 * 60 * 60),
  });

  return res(ctx.json({ accessToken: token, refreshToken }));
});
